package com.logInterceptor.model;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class AuditLog {

    public static void logEvent(String message, Auditable entity, Session session) {
        Session tempSession = null;
        Transaction tx = null;
        System.out.println("================logEvent===================");
        try {
            SessionFactory sessionFactory = session.getSessionFactory();
            tempSession = sessionFactory.openSession();
            tx = tempSession.beginTransaction();
            AuditLogRecord record = new AuditLogRecord(message, entity.getId(), entity.getClass());
            tempSession.save(record);
            tx.commit();
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            try {
                assert tempSession != null;
                tempSession.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

